package com.yssoft.service.production;


import org.apache.commons.codec.DecoderException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.yssoft.entity.core.TTechnicIndex;
import com.yssoft.entity.production.TLabelApply;
import com.yssoft.entity.production.TLabels;
import com.yssoft.entity.production.TPackageCode;
import com.yssoft.entity.production.TTechnologyGather;
import com.yssoft.entity.production.TTechnologyGatherAtt;
import com.yssoft.entity.production.TWorksheet;
import com.yssoft.mapper.core.TProcessingTechnologyMapper;
import com.yssoft.mapper.core.TTechnicIndexMapper;
import com.yssoft.mapper.production.TLabelApplyMapper;
import com.yssoft.mapper.production.TLabelsMapper;
import com.yssoft.mapper.production.TPackageCodeMapper;
import com.yssoft.mapper.production.TTechnologyGatherAttMapper;
import com.yssoft.mapper.production.TTechnologyGatherMapper;
import com.yssoft.mapper.production.TWorksheetMapper;
import com.yssoft.utils.AppUserHelper;
import com.yssoft.utils.AppUtil;
import com.yssoft.utils.UploadFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @创建人 陈翼东
 * @说明 生产过程service
 * @时间 2018/5/9 上午 11:02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProductionProcessService {

    private static Logger logger = Logger.getLogger(ProductionProcessService.class);
    /**
     * 加工工艺
     */
    @Resource
    private TProcessingTechnologyMapper processingTechnologyMapper;
    /**
     * 工艺指标
     */
    @Resource
    private TTechnicIndexMapper tTechnicIndexMapper;
    /**
     * 指标值
     */
    @Resource
    private TTechnologyGatherMapper tTechnologyGatherMapper;
    /**
     * 指标值附件
     */
    @Resource
    private TTechnologyGatherAttMapper tTechnologyGatherAttMapper;
    /**
     * 加工单
     */
    @Resource
    private TWorksheetMapper worksheetMapper;
    /**
     * 标签
     */
    @Resource
    private TLabelsMapper labelsMapper;
    /**
     * 标签申请表
     */
    @Resource
    private TLabelApplyMapper labelApplyMapper;
    /**
     * 包装码
     */
    @Resource
    private TPackageCodeMapper packageCodeMapper;

    /**
     * @方法名: findTechnologyByProduct
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 01:20
     * @参数: productId成品id
     * @返回值: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @说明: 根据成品id，查询加工工艺
     */
    public List<Map<String, Object>> findTechnologyByProduct(Integer productId, HttpServletRequest request) {
        Integer companyId = AppUserHelper.getCurrentCompanyId(request);
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("companyId", companyId);
        return processingTechnologyMapper.selectByProduct(params);
    }

    /**
     * @方法名: findIndexAndValueByProcessingTechnic
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 01:20
     * @参数: technologyId 加工工艺id
     * @返回值: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @说明: 根据加工工艺查询工艺的指标及指标值
     */
    public List<Map<String, Object>> findIndexAndValueByProcessingTechnic(String technologyId, Integer workId) {
        List<Map<String, Object>> mapList = tTechnicIndexMapper.queryIndexAndValueByProcessingTechnicAndWorkId(Integer.parseInt(technologyId), workId);
        if (mapList.isEmpty()) {
            return tTechnicIndexMapper.selectIndexAndValueByProcessingTechnic(Integer.parseInt(technologyId),workId);
        }
        return mapList;
    }

    /**
     * @方法名: findIndexByProcessingTechnic
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 01:20
     * @参数: technologyId 加工工艺id
     * @返回值: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @说明: 根据加工工艺查询工艺的指标
     */
    public List<Map<String, Object>> findIndexByProcessingTechnic(String technologyId) {
        return tTechnicIndexMapper.selectByProcessingTechnic(Integer.parseInt(technologyId));
    }


    /**
     * @方法名: addTechnologyIndicators
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 02:07
     * @参数: [indicatorIds, gValue, tWorksheeId] [工艺指标的id,加工单id]
     * @返回值: void
     * @说明: 保存工艺指标值信息和附件的信息
     */
    public Object addTechnologyIndicators(String[] indicatorIds, String tWorksheeId, HttpServletRequest request) throws IOException, DecoderException {
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (indicatorIds == null || indicatorIds.length <= 0) {
            return AppUtil.returnMapJson("0", "请传递工艺指标的id", null);
        }
        for (int i = 0; i < indicatorIds.length; i++) {
            TTechnicIndex tTechnicIndex = null;
            try {
                tTechnicIndex = tTechnicIndexMapper.selectByPrimaryKey(Integer.parseInt(indicatorIds[i]));
            } catch (NumberFormatException e) {
                return AppUtil.returnMapJson("0", "工艺指标表的id类型转换错误", null);
            }
            //新增的时候值是空的不添加
            String values = request.getParameter(indicatorIds[i] + "Value");
            MultipartHttpServletRequest mRequest1 = (MultipartHttpServletRequest) request;
            MultipartFile mFile1 = mRequest1.getFile(indicatorIds[i] + "Value");
            if ((values != null && values.length() > 0) || (mFile1 != null && mFile1.getOriginalFilename().length() > 0)) {//填写的存储，没值的不添加
                //工艺指标值
                TTechnologyGather tTechnologyGather = new TTechnologyGather();
                tTechnologyGather.setDeptId(AppUserHelper.getCurrentDeptId(request));
                tTechnologyGather.setDeptName(AppUserHelper.getCurrentDeptName(request));
                tTechnologyGather.settEId(AppUserHelper.getCurrentUserId(request));
                tTechnologyGather.settTId(Integer.parseInt(indicatorIds[i]));
                if (tWorksheeId == null) {
                    return AppUtil.returnMapJson("0", "没有传递加工单的id", null);
                }
                tTechnologyGather.settWorksheeId(Integer.parseInt(tWorksheeId));
                tTechnologyGather.setCreateTime(new Date());
                tTechnologyGather.setCreatorId(AppUserHelper.getCurrentUserId(request));
                tTechnologyGather.setCreatorName(AppUserHelper.getCurrentUserName(request));
                tTechnologyGather.setDeleteFlag("0");
                tTechnologyGatherMapper.insert(tTechnologyGather);
                if (tTechnicIndex != null) {
                    switch (tTechnicIndex.getQuota_type()) {
                        case "1"://字符
                            tTechnologyGather.setgValue(request.getParameter(indicatorIds[i] + "Value"));
                            break;
                        case "2"://数值
                            tTechnologyGather.setgValue(request.getParameter(indicatorIds[i] + "Value"));
                            break;
                        case "3"://日期

                            String value = request.getParameter(indicatorIds[i] + "Value");
                            if (value != null) {
                                tTechnologyGather.setgValue(value);
                            } else {
                                tTechnologyGather.setgValue("");
                            }

                            break;
                        case "4"://日期时间
                            String value2 = request.getParameter(indicatorIds[i] + "Value");
                            if (value2 != null) {
                                tTechnologyGather.setgValue(value2);
                            } else {
                                tTechnologyGather.setgValue("");
                            }
                            break;
                        case "5"://图片
                            try {
                                MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
                                MultipartFile mFile = mRequest.getFile(indicatorIds[i] + "Value");
                                if (mFile != null && mFile.getOriginalFilename().length() > 0) {
                                    //删除原来的图片
                                    List<TTechnologyGatherAtt> attList = tTechnologyGatherAttMapper.selectByTechnologyGather(tTechnologyGather.getId());
                                    for (TTechnologyGatherAtt att2 : attList) {
                                        att2.setDeleteFlag("1");
                                        tTechnologyGatherAttMapper.updateByPrimaryKeySelective(att2);
                                    }
                                    TTechnologyGatherAtt att = new TTechnologyGatherAtt();//附件表
                                    att.settTGId(tTechnologyGather.getId());
                                    att.setDeptId(AppUserHelper.getCurrentDeptId(request));
                                    att.setDeptName(AppUserHelper.getCurrentDeptName(request));
                                    att.settEId(AppUserHelper.getCurrentCompanyId(request));
                                    Map<String, Object> urlMap = UploadFile.compressUploadedFile(mFile);
                                    att.setTurl(urlMap.get("thumbnails") + "");
                                    att.setUrl(urlMap.get("fileName") + "");
                                    att.setType("5");
                                    att.setCreateTime(new Date());
                                    att.setCreatorId(AppUserHelper.getCurrentUserId(request));
                                    att.setCreatorName(AppUserHelper.getCurrentUserName(request));
                                    att.setDeleteFlag("0");
                                    tTechnologyGatherAttMapper.insert(att);
                                }

                            } catch (Exception e) {
                                logger.error("工艺指标值上传图片失败" + e.getMessage());
                                return AppUtil.returnMapJson("0", "工艺指标值上传图片失败", null);
                            }
                            break;
                        case "6"://音视频
                            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
                            try {
                                MultipartFile mFile = mRequest.getFile(indicatorIds[i] + "Value");
                                if (mFile != null && mFile.getOriginalFilename().length() > 0) {
                                    List<TTechnologyGatherAtt> attList2 = tTechnologyGatherAttMapper.selectByTechnologyGather(tTechnologyGather.getId());
                                    for (TTechnologyGatherAtt att2 : attList2) {
                                        att2.setDeleteFlag("1");
                                        tTechnologyGatherAttMapper.updateByPrimaryKeySelective(att2);
                                    }
                                    TTechnologyGatherAtt att = new TTechnologyGatherAtt();//附件表
                                    att.settTGId(tTechnologyGather.getId());
                                    att.setDeptId(AppUserHelper.getCurrentDeptId(request));
                                    att.setDeptName(AppUserHelper.getCurrentDeptName(request));
                                    att.settEId(AppUserHelper.getCurrentCompanyId(request));
                                    Map<String, Object> urlMap = UploadFile.compressUploadedFile(mFile);
                                    att.setTurl(urlMap.get("thumbnails") + "");
                                    att.setUrl(urlMap.get("fileName") + "");
                                    att.setType("6");
                                    att.setCreateTime(new Date());
                                    att.setCreatorId(AppUserHelper.getCurrentUserId(request));
                                    att.setCreatorName(AppUserHelper.getCurrentUserName(request));
                                    att.setDeleteFlag("0");
                                    tTechnologyGatherAttMapper.insert(att);
                                }
                            } catch (Exception e) {
                                logger.error("工艺指标值上传音频失败" + e.getMessage());
                                return AppUtil.returnMapJson("0", "工艺指标值上传音频失败", null);
                            }
                            break;
                        default:
                            return AppUtil.returnMapJson("0", "工艺指标中值类型没有定义", null);
                    }
                    tTechnologyGatherMapper.updateByPrimaryKeySelective(tTechnologyGather);
                } else {
                    return AppUtil.returnMapJson("0", "工艺指标对应的id:" + indicatorIds[i] + "没有查询出数据", null);
                }
            }
        }
        return AppUtil.returnMapJson("1", "保存成功!", null);
    }


    /**
     * @方法名: addTechnologyIndicators
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 02:07
     * @参数: [indicatorIds, gValue, tWorksheeId] [工艺指标的id,加工单id]
     * @返回值: void
     * @说明: 修改工艺指标值信息和附件的信息
     */
    public Object editTechnologyIndicators(String[] indicatorIds, String tWorksheeId, HttpServletRequest request) throws IOException, DecoderException, ParseException {
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (indicatorIds == null || indicatorIds.length <= 0) {
            return AppUtil.returnMapJson("0", "请传递工艺指标的id", null);
        }
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        for (int i = 0; i < indicatorIds.length; i++) {

            TTechnicIndex tTechnicIndex = null;
            MultipartFile mFile2 = mRequest.getFile(indicatorIds[i] + "Value");
            try {
                tTechnicIndex = tTechnicIndexMapper.selectByPrimaryKey(Integer.parseInt(indicatorIds[i]));
            } catch (NumberFormatException e) {
                return AppUtil.returnMapJson("0", "工艺指标表的id类型转换错误", null);
            }

            String valuesid = request.getParameter(indicatorIds[i] + "valuesid").equals("") ? "0" : request.getParameter(indicatorIds[i] + "valuesid");
            //按工艺采集表ID和工单ID获取工艺采集信息
            TTechnologyGather tTechnologyGather = tTechnologyGatherMapper.queryTechnologyGatherInfo(Integer.parseInt(valuesid), Integer.parseInt(tWorksheeId));
//            if (valuesid != null && valuesid.length() > 0) {//修改以前的有值的
//                //工艺指标值
//                tTechnologyGather = tTechnologyGatherMapper.selectByPrimaryKey(Integer.parseInt(valuesid));
//            } else
            if (tTechnologyGather == null) {
                tTechnologyGather = new TTechnologyGather();
                tTechnologyGather.setDeptId(AppUserHelper.getCurrentDeptId(request));
                tTechnologyGather.setDeptName(AppUserHelper.getCurrentDeptName(request));
                tTechnologyGather.settEId(AppUserHelper.getCurrentUserId(request));
                tTechnologyGather.settTId(Integer.parseInt(indicatorIds[i]));
                //工单ID
                tTechnologyGather.settWorksheeId(Integer.parseInt(tWorksheeId));
                tTechnologyGather.setCreateTime(new Date());
                tTechnologyGather.setCreatorId(AppUserHelper.getCurrentUserId(request));
                tTechnologyGather.setCreatorName(AppUserHelper.getCurrentUserName(request));
                tTechnologyGather.setDeleteFlag("0");
            }
            if (tTechnicIndex != null) {
                switch (tTechnicIndex.getQuota_type()) {
                    case "1"://字符
                        String value = request.getParameter(indicatorIds[i] + "Value");
                        if (value == null) {
                            tTechnologyGather.setgValue("");
                        } else {
                            tTechnologyGather.setgValue(value);
                        }
                        break;
                    case "2"://数值
                        String value2 = request.getParameter(indicatorIds[i] + "Value");
                        if (value2 == null) {
                            tTechnologyGather.setgValue("");
                        } else {
                            tTechnologyGather.setgValue(value2);
                        }
                        break;
                    case "3"://日期

                        if (request.getParameter(indicatorIds[i] + "Value") != null && request.getParameter(indicatorIds[i] + "Value").length() > 0) {
                            tTechnologyGather.setgValue(request.getParameter(indicatorIds[i] + "Value") + "");
                        } else {
                            tTechnologyGather.setgValue("");
                        }

                        break;
                    case "4"://日期时间
                        if (request.getParameter(indicatorIds[i] + "Value") != null && request.getParameter(indicatorIds[i] + "Value").length() > 0) {
                            tTechnologyGather.setgValue(request.getParameter(indicatorIds[i] + "Value"));
                        } else {
                            tTechnologyGather.setgValue("");
                        }
                        break;
                    case "5"://图片
                        try {

                            if (mFile2 != null && mFile2.getOriginalFilename().length() > 0) {
                                //删除原来的图片
                                List<TTechnologyGatherAtt> attList = tTechnologyGatherAttMapper.selectByTechnologyGather(tTechnologyGather.getId());
                                for (TTechnologyGatherAtt att2 : attList) {
                                    tTechnologyGatherAttMapper.delete(att2);
                                }
                                if (tTechnologyGather.getId() == null) {
                                    tTechnologyGatherMapper.insert(tTechnologyGather);
                                }
                                TTechnologyGatherAtt att = new TTechnologyGatherAtt();//附件表
                                att.settTGId(tTechnologyGather.getId());
                                att.setDeptId(AppUserHelper.getCurrentDeptId(request));
                                att.setDeptName(AppUserHelper.getCurrentDeptName(request));
                                att.settEId(AppUserHelper.getCurrentCompanyId(request));
                                Map<String, Object> urlMap = UploadFile.compressUploadedFile(mFile2);
                                att.setTurl(urlMap.get("thumbnails") + "");
                                att.setUrl(urlMap.get("fileName") + "");
                                att.setType("5");
                                att.setCreateTime(new Date());
                                att.setCreatorId(AppUserHelper.getCurrentUserId(request));
                                att.setCreatorName(AppUserHelper.getCurrentUserName(request));
                                att.setDeleteFlag("0");
                                tTechnologyGatherAttMapper.insert(att);
                            }
                            break;
                        } catch (Exception e) {
                            logger.error("工艺指标值上传图片失败" + e.getMessage());
                            return AppUtil.returnMapJson("0", "工艺指标值上传图片失败", null);
                        }

                    case "6"://音视频
                        try {


                            if (mFile2 != null && mFile2.getOriginalFilename().length() > 0) {
                                List<TTechnologyGatherAtt> attList2 = tTechnologyGatherAttMapper.selectByTechnologyGather(tTechnologyGather.getId());
                                for (TTechnologyGatherAtt att2 : attList2) {
                                    tTechnologyGatherAttMapper.delete(att2);
                                }
                                if (tTechnologyGather.getId() == null) {
                                    tTechnologyGatherMapper.insert(tTechnologyGather);
                                }
                                TTechnologyGatherAtt att = new TTechnologyGatherAtt();//附件表
                                att.settTGId(tTechnologyGather.getId());
                                att.setDeptId(AppUserHelper.getCurrentDeptId(request));
                                att.setDeptName(AppUserHelper.getCurrentDeptName(request));
                                att.settEId(AppUserHelper.getCurrentCompanyId(request));
                                String urlMap = UploadFile.processUploadedVideo(mFile2);
                                att.setTurl(urlMap);
                                att.setUrl(urlMap);
                                att.setType("6");
                                att.setCreateTime(new Date());
                                att.setCreatorId(AppUserHelper.getCurrentUserId(request));
                                att.setCreatorName(AppUserHelper.getCurrentUserName(request));
                                att.setDeleteFlag("0");
                                tTechnologyGatherAttMapper.insert(att);
                            }

                            break;
                        } catch (Exception e) {
                            logger.error("工艺指标值上传音频失败" + e.getMessage());
                            return AppUtil.returnMapJson("0", "工艺指标值上传音频失败", null);
                        }
                    default:
                        return AppUtil.returnMapJson("0", "工艺指标中值类型没有定义", null);
                }
                if (tTechnologyGather.getId() == null) {
                    tTechnologyGatherMapper.insert(tTechnologyGather);
                } else {
                    tTechnologyGatherMapper.updateByPrimaryKeySelective(tTechnologyGather);
                }


            } else {
                return AppUtil.returnMapJson("0", "工艺指标对应的id:" + indicatorIds[i] + "没有查询出数据", null);
            }
        }
        return AppUtil.returnMapJson("1", "保存成功!", null);
    }


    /**
     * @方法名: findWorksheetAndProducts
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 03:39
     * @参数: [worksheetId]
     * @返回值: java.util.Map<java.lang.String, java.lang.Object>
     * @说明: 查询加工单信息和批次码和成品溯源类型
     */
    public List<Map<String, Object>> findWorksheetAndProducts(String worksheetId) {
        return worksheetMapper.selectWorksheetAndProducts(worksheetId);
    }

    /**
     * @方法名: findBatchAndSourcetype
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 04:32
     * @参数: [code] 标签码
     * @返回值: java.util.Map<java.lang.String, java.lang.Object>
     * @说明: 获取标签码对应的批次信息, 溯源类型信息
     */
    public Map<String, Object> findBatchAndSourceType(String code) {
        return labelsMapper.selectLableBatchAndSourceType(code);
    }

    /**
     * @方法名: findHistoryLableByPackageCode
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 04:50
     * @参数: [packageCode]
     * @返回值: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @说明: 根据包装码查询该包装码扫描过的标签码
     */
    public List<Map<String, Object>> findHistoryLableByPackageCode(String packageCode) {
        return labelsMapper.selectByPackageCode(packageCode);
    }

    /**
     * @方法名: saveSemiFinishedProductNum
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 05:01
     * @参数: [num, worksheetId] 输入的实际数量, 加工单id
     * @返回值: void
     * @说明: 半成品的加工单实际生产数量保存
     */
    public Object saveSemiFinishedProductNum(String num, String worksheetId) {
        if (worksheetId == null || worksheetId.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递加工单的id", null);
        }
        if (num == null || num.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递已生产数量", null);
        }
        try {
            TWorksheet worksheet = worksheetMapper.selectByPrimaryKey(Integer.parseInt(worksheetId));
            String actualOutput = worksheet.getActualOutput();//原来的实际加工数量
            int oldNum = 0;
            if (actualOutput != null && actualOutput.length() >= 0) {
                oldNum = Integer.parseInt(actualOutput);
            }
            int newNum = Integer.parseInt(num);
            worksheet.setActualOutput((newNum + oldNum) + "");
            worksheetMapper.updateByPrimaryKeySelective(worksheet);//保存加工单中加工数量

            return AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (NumberFormatException e) {
            logger.error("保存半成品实际生产数量失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }

    }

    /**
     * @方法名: saveBatchScan
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 05:16
     * @参数: [lableCode, batchNum, worksheetId] 标签码,加工数量,加工单id
     * @返回值: java.lang.Object
     * @说明: 批次溯源类型的商品扫码之后保存
     */
    public Object saveBatchScan(String lableCode, String batchNum, String worksheetId, HttpServletRequest request) {
        if (lableCode == null || lableCode.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递标签码", null);
        }
        if (batchNum == null || batchNum.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递商品数量", null);
        }
        if (worksheetId == null || worksheetId.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递加工单id", null);
        }
        TLabels labels = labelsMapper.selectByCode(lableCode);
        try {
            TWorksheet worksheet = worksheetMapper.selectByPrimaryKey(Integer.parseInt(worksheetId));
            String actualOutput = worksheet.getActualOutput();//原来的实际加工数量
            int oldNum = 0;
            if (actualOutput != null && actualOutput.length() >= 0) {
                if (actualOutput.indexOf(".") >= 0) {
                    actualOutput = actualOutput.substring(0, actualOutput.indexOf("."));
                }
                oldNum = Integer.parseInt(actualOutput);
            }
            int newNum = Integer.parseInt(batchNum);
            worksheet.setActualOutput((newNum + oldNum) + "");
            worksheetMapper.updateByPrimaryKeySelective(worksheet);//保存加工单中加工数量

            TPackageCode packageCodeEntity = new TPackageCode();//新增一个空的包装码，用来给扫描历史
            packageCodeEntity.settWorksheeId(worksheet.getId());//保存包装码和加工单关系
            packageCodeEntity.setScanPerson(AppUserHelper.getCurrentUserName(request));
            packageCodeEntity.setScanTime(new Date());
            packageCodeEntity.setQuantity(oldNum);
            packageCodeEntity.setDeleteFlag("0");
            packageCodeEntity.setCreateTime(new Date());
            packageCodeEntity.setCreatorId(AppUserHelper.getCurrentUserId(request));
            packageCodeEntity.setCreatorName(AppUserHelper.getCurrentUserName(request));
            packageCodeEntity.settEId(AppUserHelper.getCurrentCompanyId(request));
            packageCodeEntity.setDeptId(AppUserHelper.getCurrentDeptId(request));
            packageCodeEntity.setDeptName(AppUserHelper.getCurrentDeptName(request));
            packageCodeMapper.insert(packageCodeEntity);

            labels.settPackageId(packageCodeEntity.getId());
            labels.settWorksheeId(worksheet.getId());
            labelsMapper.updateByPrimaryKeySelective(labels);
            //修改标签申请表中已用数量
            TLabelApply labelApply = labelApplyMapper.selectByPrimaryKey(labels.gettLabelAppId());
            BigDecimal oldUserQ = labelApply.getUsedQuantity();
            BigDecimal newUserQ = new BigDecimal(batchNum);
            labelApply.setUsedQuantity(oldUserQ.add(newUserQ));
            labelApplyMapper.updateByPrimaryKeySelective(labelApply);
            return AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (NumberFormatException e) {
            logger.error("保存批次溯源实际生产数量失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }
    }

    /**
     * @方法名: getPackageNumber
     * @创建人: 陈翼东
     * @时间: 2018/5/9 下午 07:54
     * @参数: [packageCode]
     * @返回值: java.util.Map<java.lang.String, java.lang.Object>
     * @说明: 包材的获取包装数量
     */
    public Map<String, Object> getPackageNumber(String packageCode, String worksheetId) {
        Map<String, String> param = new HashMap<>();
        param.put("packageCode", packageCode);
        param.put("worksheetId", worksheetId);
        Map<String, Object> result = packageCodeMapper.selectPackageNumber(param);
        return result;
    }

    /**
     * @方法名: saveUnitNoPackage
     * @创建人: 陈翼东
     * @时间: 2018/5/10 上午 08:41
     * @参数: [lableCode, worksheetId]
     * @返回值: java.lang.Object
     * @说明: 个体溯源无包装码方式扫码保存
     */
    public Object saveUnitNoPackage(String[] lableCode, String worksheetId, HttpServletRequest request) {
        if (lableCode == null || lableCode.length <= 0) {
            return AppUtil.returnMapJson("0", "请传递标签码", null);
        }
        if (worksheetId == null || worksheetId.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递加工单id", null);
        }
        try {
            TLabels firstLabels = null;
            for (String code : lableCode) {
                TWorksheet worksheet = worksheetMapper.selectByPrimaryKey(Integer.parseInt(worksheetId));//加工单
                String actualOutput = worksheet.getActualOutput();//原来的实际加工数量
                int oldNum = 0;
                if (actualOutput != null && actualOutput.length() >= 0) {
                    if (actualOutput.indexOf(".") >= 0) {
                        actualOutput = actualOutput.substring(0, actualOutput.indexOf("."));
                    }
                    oldNum = Integer.parseInt(actualOutput);
                }
                worksheet.setActualOutput((lableCode.length + oldNum) + "");
                worksheetMapper.updateByPrimaryKeySelective(worksheet);//保存加工单中加工数量

                TPackageCode packageCodeEntity = new TPackageCode();//新增一个空的包装码，用来给扫描历史
                packageCodeEntity.settWorksheeId(worksheet.getId());//保存包装码和加工单关系
                packageCodeEntity.setScanPerson(AppUserHelper.getCurrentUserName(request));
                packageCodeEntity.setScanTime(new Date());
                packageCodeEntity.setQuantity(lableCode.length);
                packageCodeEntity.setDeleteFlag("0");
                packageCodeEntity.setCreateTime(new Date());
                packageCodeEntity.setCreatorId(AppUserHelper.getCurrentUserId(request));
                packageCodeEntity.setCreatorName(AppUserHelper.getCurrentUserName(request));
                packageCodeEntity.settEId(AppUserHelper.getCurrentCompanyId(request));
                packageCodeEntity.setDeptId(AppUserHelper.getCurrentDeptId(request));
                packageCodeEntity.setDeptName(AppUserHelper.getCurrentDeptName(request));
                packageCodeMapper.insert(packageCodeEntity);


                TLabels labels = labelsMapper.selectByCode(code);//个体码
                firstLabels = labels;
                labels.settWorksheeId(worksheet.getId());
                labels.settPackageId(packageCodeEntity.getId());
                labelsMapper.updateByPrimaryKeySelective(labels);//保存标签码和包装码关系
            }
            //修改标签申请表中已用数量
            TLabelApply labelApply = labelApplyMapper.selectByPrimaryKey(firstLabels.gettLabelAppId());
            BigDecimal oldUserQ = labelApply.getUsedQuantity();
            BigDecimal newUserQ = new BigDecimal(lableCode.length);
            labelApply.setUsedQuantity(oldUserQ.add(newUserQ));
            labelApplyMapper.updateByPrimaryKeySelective(labelApply);
            return AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (NumberFormatException e) {
            logger.error("保存批次溯源实际生产数量失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }
    }

    /**
     * @方法名: saveUnitIsPackage
     * @创建人: 陈翼东
     * @时间: 2018/5/10 上午 08:43
     * @参数: [packageCode, lableCode, worksheetId] 包装码 ,标签码,加工单id
     * @返回值: java.lang.Object
     * @说明: 个体溯源有包装码方式扫码保存
     */
    public Object saveUnitIsPackage(String packageCode, String[] lableCode, String worksheetId, HttpServletRequest request) {
        if (packageCode == null || packageCode.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递包装码", null);
        }
        if (worksheetId == null || worksheetId.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递加工单id", null);
        }
        if (lableCode == null || lableCode.length <= 0) {
            return AppUtil.returnMapJson("0", "请传递标签码", null);
        }
        try {
            TWorksheet worksheet = worksheetMapper.selectByPrimaryKey(Integer.parseInt(worksheetId));//获取加工单
            TPackageCode packageCodeEntity = packageCodeMapper.selectPackageCodeByCode(packageCode);
            //------判断商品扫描数是否超出包装数-----------------------
//            Map<String, Object> packageNumber = getPackageNumber(packageCode, worksheetId);//获取包装能够打包的商品数量
//            Object oldScanNumber = findHistoryLableByPackageCode(packageCode);//原来包装扫过的标签码
//            if (packageNumber != null) {
//                Object number = packageNumber.get("package_num");
//                if (number != null) {
//                    if (oldScanNumber == null) {
//                        return AppUtil.returnMapJson("0", "获取包装扫过的商品数量失败!", null);
//                    } else {
//                        if (Integer.parseInt(oldScanNumber.toString()) + lableCode.length > Integer.parseInt(number.toString())) {
//                            return AppUtil.returnMapJson("0", "实际扫描数量大于了包装数量", null);
//                        }
//                    }
//                } else {
//                    return AppUtil.returnMapJson("0", "获取包装的包装数量失败!", null);
//                }
//            } else {
//                return AppUtil.returnMapJson("0", "获取包装的包装数量失败!", null);
//            }
            //------------------------------------------------------
            int oldNum = 0;
            String actualOutput = worksheet.getActualOutput();//原来的实际加工数量
            if (actualOutput != null && actualOutput.length() >= 0) {
                if (actualOutput.indexOf(".") >= 0) {
                    actualOutput = actualOutput.substring(0, actualOutput.indexOf("."));
                }
                oldNum = Integer.parseInt(actualOutput);
            }
            int newNum = lableCode.length + oldNum;

            worksheet.setActualOutput(newNum + "");//添加实际加工数量
            worksheetMapper.updateByPrimaryKeySelective(worksheet);
            packageCodeEntity.settWorksheeId(worksheet.getId());//保存包装码和加工单关系
            packageCodeEntity.setScanPerson(AppUserHelper.getCurrentUserName(request));
            packageCodeEntity.setScanTime(new Date());
            packageCodeEntity.setQuantity(lableCode.length);
            packageCodeMapper.updateByPrimaryKeySelective(packageCodeEntity);
            TLabels oneLable = null;
            for (String lable : lableCode) {
                TLabels labels = labelsMapper.selectByCode(lable);//获取标签码
                oneLable = labels;
                labels.settPackageId(packageCodeEntity.getId());
                labelsMapper.updateByPrimaryKeySelective(labels);//保存标签码和包装码关系
            }

            //修改标签申请表中已用数量
            TLabelApply labelApply = labelApplyMapper.selectByPrimaryKey(oneLable.gettLabelAppId());
            BigDecimal oldUserQ = labelApply.getUsedQuantity();
            BigDecimal newUserQ = new BigDecimal(lableCode.length);
            labelApply.setUsedQuantity(oldUserQ.add(newUserQ));
            labelApplyMapper.updateByPrimaryKeySelective(labelApply);
            return AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (NumberFormatException e) {
            logger.error("保存批次溯源实际生产数量失败" + e.getMessage());
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }

    }

    /**
     * @方法名: getWorksheetScanHistory
     * @创建人: 陈翼东
     * @时间: 2018/5/12 上午 09:53
     * @参数: [worksheetId]
     * @返回值: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @说明: 获取加工单扫描历史
     */
    public List<Map<String, Object>> getWorksheetScanHistory(String worksheetId) {
        List<Map<String, Object>> packageCodes = packageCodeMapper.selectByWorksheet(worksheetId);
        for (Map<String, Object> packageCode : packageCodes) {
            List<Map<String, Object>> lable = labelsMapper.selectByPackageId(packageCode.get("id").toString());
            packageCode.put("lables", lable);
        }
        return packageCodes;
    }

    /**
     * @方法名: getworksheetByPackage
     * @创建人: 陈翼东
     * @时间: 2018/5/12 上午 11:39
     * @参数: [packageCode]
     * @返回值: java.util.Map<java.lang.String, java.lang.Object>
     * @说明: 根据包装码获取加工单
     */
    public Map<String, Object> getworksheetByPackage(String packageCode) {
        return worksheetMapper.selectByPackageCode(packageCode);
    }

    /**
     * @方法名: packageIsWorksheet
     * @创建人: 陈翼东
     * @时间: 2018/5/12 下午 03:37
     * @参数: [packageCode]
     * @返回值: java.lang.Object
     * @说明: 1.5.    查询包装码时是否是当前加工单，是否被扫描过
     */
    public TPackageCode getPackageByCode(String packageCode) {
        return packageCodeMapper.selectPackageCodeByCode(packageCode);
    }

    /**
     * 根据图片路径删除图片
     *
     * @param newFileUrl
     */
    public void deleteFileByUrl(String newFileUrl) {
        tTechnologyGatherAttMapper.deleteByUrl(newFileUrl);
    }
}
